import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  getUserMenu
} from '@/api/menu'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 生成用户菜单路由
 * @param routes asyncRoutes
 * @param roles
 */
function generateUserMenu(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    // views
    const componentTmp = tmp.component
    if (componentTmp) {
      tmp.component = (resolve) => require([`@/views${componentTmp}`], resolve)
    }
    if (tmp.children) {
      tmp.children = generateUserMenu(tmp.children)
    }
    res.push(tmp)
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 将用户菜单接口数据与本地路由合并
      getUserMenu().then(res => {
        let accessedRoutes
        const userRoutes = generateUserMenu(res.data.items)
        const newAsyncRoutes = [...userRoutes, ...asyncRoutes]
        if (roles.includes('admin')) {
          accessedRoutes = newAsyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(newAsyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
